package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.DTO.app.AppConsumeRecordDTO;
import com.itlong.cloud.POJO.DTO.property.ConsumptionRecordDTO;
import com.itlong.cloud.POJO.VO.app.AppElevatorConsumptionRecordInfoVO;
import com.itlong.cloud.POJO.VO.app.AppElevatorConsumptionRecordVO;
import com.itlong.cloud.POJO.VO.property.ConsumptionRecordVO;
import com.itlong.cloud.property.dao.IPropertyConsumptionDao;
import com.itlong.cloud.property.service.IPropertyConsumptionService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      消费管理服务层接口实现类
 * </desc>
 *
 * @createDate2020/7/15
 **/
@Service
public class PropertyConsumptionServiceImpl implements IPropertyConsumptionService {

    @Autowired
    private IPropertyConsumptionDao iPropertyConsumptionDao;
    /**
     * <desc>
     *      分页获取消费管理列表
     * </desc>
     *
     * @param consumptionRecordDTO 消费记录DTO
     * @return 消费记录分页列表
     * @Author Zhu.yj
     * @createDate  2020/7/16
     */
    @Override
    public Page<ConsumptionRecordVO> getPage(ConsumptionRecordDTO consumptionRecordDTO) throws Exception {
        if (StringUtils.isBlank(consumptionRecordDTO.getOrderColumn())){
            consumptionRecordDTO.setOrderColumn("createTime");
            consumptionRecordDTO.setOrderRule("DESC");
        }
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(consumptionRecordDTO);
        List<String> passType = StringHandlerUtil.splitStringList(consumptionRecordDTO.getPassType());
        List<String> houseType = StringHandlerUtil.splitStringList(consumptionRecordDTO.getHouseType());
        Page<ConsumptionRecordVO> page = new Page<>();
        page.getPage().setCurrentPage(consumptionRecordDTO.getCurrentPage());
        page.getPage().setPageSize(consumptionRecordDTO.getPageSize());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        params.put("passType", passType);
        params.put("houseType", houseType);
        page.setRows(iPropertyConsumptionDao.getPage(params), iPropertyConsumptionDao.getPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      app获取消费记录列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2020/7/17
     */
    @Override
    public List<AppElevatorConsumptionRecordVO> getLiftConsumeRecord(AppConsumeRecordDTO appConsumeRecordDTO) throws Exception{
        if("0".equals(appConsumeRecordDTO.getUserType())){
            appConsumeRecordDTO.setUserType(null);
        }
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(appConsumeRecordDTO);
        if ("0".equals(appConsumeRecordDTO.getUserType())){
            params.put("userType", null);
        }
        List<AppElevatorConsumptionRecordVO> list = new ArrayList<>();
        Page<AppElevatorConsumptionRecordVO> page = new Page<>();
        page.getPage().setPageSize("15");
        page.getPage().setCurrentPage(appConsumeRecordDTO.getPageNum());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<ConsumptionRecordVO> recordDate = iPropertyConsumptionDao.getRecordDate(params);
        if (recordDate != null && !recordDate.isEmpty()){
            for (ConsumptionRecordVO consumptionRecordVO :recordDate){
                AppElevatorConsumptionRecordVO recordVO = new AppElevatorConsumptionRecordVO();
                List<String> consumeIdList = StringHandlerUtil.splitStringList(consumptionRecordVO.getConsumeId());
                recordVO.setMonth(consumptionRecordVO.getCreateTime());
                recordVO.setConsumeList(iPropertyConsumptionDao.getRecordList(consumeIdList));
                list.add(recordVO);
            }
        }
        return list;
    }

    /**
     * <desc>
     *      获取有缴费/消费记录的年月
     * </desc>
     *
     * @param appConsumeRecordDTO app消费记录DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/7/20
     */
    @Override
    public List<Map<String, Object>> getLiftDateRecord(AppConsumeRecordDTO appConsumeRecordDTO) throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<Map<String, Object>> dateList = new ArrayList<>();
        params.put("projectId", appConsumeRecordDTO.getProjectId());
        params.put("roomId", appConsumeRecordDTO.getRoomId());
        if ("1".equals(appConsumeRecordDTO.getType())){
            dateList = iPropertyConsumptionDao.getConsumptionDate(params);
        }
        if ("2".equals(appConsumeRecordDTO.getType())){
            dateList = iPropertyConsumptionDao.getPaymentDate(params);
        }
        return dateList;
    }
    public static void main(String[] args) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date d = sdf.parse("2021-04-01".trim());
        Date d = new Date();
        int count = differentDays(d,DateUtil.getAddMonth(d,1));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 定义数组
        String[]time1=new String[32];
        Map<String,List<String>> monthMap = new HashMap<>();
        Map<String,Object> yearMap = new HashMap<>();
        Set<String> set = new HashSet<>();
        Set<String> set1 = new HashSet<>();
        for(int i=0;i<=count;i++){
            Date date = d;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + i);
            // 设置为前i天 
            date = calendar.getTime();
            //将获取的日期添加的数组
            time1[count-i]=dateFormat.format(date);
            List<String> dateList = new ArrayList<>();
            set.add(time1[count-i].substring(0,7));
            set1.add(time1[count-i].substring(0,5));
            if(monthMap.containsKey(time1[count-i].substring(5,7))){
                monthMap.get(time1[count-i].substring(5,7)).add(time1[count-i].substring(8,10));
                monthMap.put(time1[count-i].substring(5,7),monthMap.get(time1[count-i].substring(5,7)));
            }else{
                dateList.add(time1[count-i].substring(8,10));
                monthMap.put(time1[count-i].substring(5,7),dateList);
            }
//            if(yearMap.containsKey(time1[count-i].substring(0,4))){
//                yearMap.remove(time1[count-i].substring(0,4)).toString();
//            }
//            yearMap.put(time1[count-i].substring(0,4).toString(),monthMap);

        }
        if(set1.size()==2){
            for (Map.Entry<String,List<String>> entry : monthMap.entrySet()){
                for(String str : set){
                    Map<String,List<String>> oldMonthMap = new HashMap<>();
                    if(str.substring(5,7).contains(entry.getKey())){
                        oldMonthMap.put(entry.getKey(),entry.getValue());
                        yearMap.put(str.substring(0,4),oldMonthMap);
                    }
                    set.remove(str);
                    break;
                }

            }
        }else{
            for(String str : set){
               yearMap.put(str.substring(0,4),monthMap);
            }
        }


//        Set<String> set = new HashSet<>();
//        for(int i=0;i<=count;i++){
//            set.add(time1[count-i].substring(0,7));
//        }
//        for(String str : set){
//            yearMap.put(str.substring(0,4),monthMap);
//        }

        System.out.println(Arrays.toString(time1));
        System.out.println(monthMap.toString());
        System.out.println(differentDays(new Date(),DateUtil.getAddMonth(new Date(),1)));
        System.out.println(set.toString());
        System.out.println(yearMap.toString());

    }

    public static String getPreMonth(String repeatDate) {
        String lastMonth = "";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMM");
        int year = Integer.parseInt(repeatDate.substring(0, 4));
        String monthsString = repeatDate.substring(4, 6);
        int month;
        if ("0".equals(monthsString.substring(0, 1))) {
            month = Integer.parseInt(monthsString.substring(1, 2));
        } else {
            month = Integer.parseInt(monthsString.substring(0, 2));
        }
        cal.set(year,month,Calendar.DATE);
        lastMonth = dft.format(cal.getTime());
        return lastMonth;
    }

    public static Date[] getDates(String year, String month) {
        int maxDate = 0;
        Date first = null;
        try {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            first = sdf.parse(year + month);
            cal.setTime(first);
            maxDate = cal.getMaximum(Calendar.DAY_OF_MONTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date[] dates = new Date[maxDate];
        for (int i = 1; i <= maxDate; i++) {
            dates[i - 1] = new Date(first.getTime());
            first.setDate(first.getDate() + 1);
        }
        return dates;
    }
    /**
     * date2比date1多的天数
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else    //不同年
        {
            System.out.println("判断day2 - day1 : " + (day2-day1));
            return day2-day1;
        }
    }
}
